package com.wfh.activity;

import com.wfh.R;
import com.wfh.service.CoreService;
import com.wfh.service.CoreService.MyBinder;
import com.wfh.util.Util;

import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;

public class WelcomeActivity extends Activity {
	private CoreService service;
	private BroadcastReceiver mReceiver = new DataReceiver();;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_welcome);

		// 注册recevier广播接收器
		IntentFilter filter = new IntentFilter();
		filter.addAction(Util.D_INIT);
		registerReceiver(mReceiver, filter);

		// 绑定service
		Util.bindservice(this, CoreService.class, conn);
	}

	@SuppressLint("HandlerLeak")
	Handler mhandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				Util.startactivity(WelcomeActivity.this, MainActivity.class);
				WelcomeActivity.this.finish();
			}
		}
	};

	// 绑定服务service
	private ServiceConnection conn = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder binder) {
			service = ((MyBinder) binder).getService();
			service.initData(WelcomeActivity.this, null);
		}
	};

	// 接收器
	private class DataReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			mhandler.sendEmptyMessageDelayed(1, 1000);
		}
	}

	// 监听返回键
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return true;
		}
		return false;
	}

	@Override
	protected void onDestroy() {
		WelcomeActivity.this.getApplicationContext().unbindService(conn);
		unregisterReceiver(mReceiver);
		super.onDestroy();
	}

}
